package com.mdata.service;

import com.mdata.common.BaseRestRequest;
import com.mdata.common.CommonCodeConstant;
import com.mdata.common.DefinitionException;
import com.mdata.common.ResponseEnum;
import com.mdata.model.dto.wechat.dto.UserDepartmentUpdateDTO;
import com.mdata.model.dto.wechat.result.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SimpleService extends CommonService {

    @Autowired
    private DepartmentService departmentService;


    /**
     * 根据部门 获取部门下所有成员Map<成员id，成员UserList>
     * @param departmentId
     */
    public Map<String, UserList> getSimpleMap(Integer departmentId){
        List<UserList> simpleList = getSimpleList(departmentId, 1);
        return simpleList.stream().collect(Collectors.toMap(o -> o.getUserId(), o -> o));
    }

    /**
     * 获取部门成员
     *
     * 请求方式：GET（HTTPS）
     * 请求地址：https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token=ACCESS_TOKEN&department_id=DEPARTMENT_ID&fetch_child=FETCH_CHILD
     *
     * 参数说明：
     * access_token 	是 	调用接口凭证
     * department_id 	是 	获取的部门id
     * fetch_child 	否 	是否递归获取子部门下面的成员：1-递归获取，0-只获取本部门
     * @return
     */
    public List<UserList> getSimpleList(Integer departmentId, Integer fetchChild){
        MultiValueMap<String, String> queryParamMap = new LinkedMultiValueMap<>();
        queryParamMap.add("department_id", departmentId.toString());
        queryParamMap.add("fetch_child", fetchChild.toString());
        String url = splicingAccessToken(getWechatAddressBookSecret(), "user/simplelist", queryParamMap);
        SimpleListResult simpleListResult = BaseRestRequest.getForObject(restTemplate, url, SimpleListResult.class);
        if(!Objects.equals(simpleListResult.getErrCode(), CommonCodeConstant.SUCCESS_CODE)){
            log.error(simpleListResult.getErrMsg());
            throw new DefinitionException(ResponseEnum.WECHAT_ERROR_GET_SIMPLE_LIST);
        }
       return simpleListResult.getUserListList();
    }

    /**
     * 更新成员
     *
     * 请求方式：POST（HTTPS）
     * 请求地址：https://qyapi.weixin.qq.com/cgi-bin/user/update?access_token=ACCESS_TOKEN
     * @param userDepartmentUpdateDTO
     * @return
     */
    public WeChatBaseResult updateUserDepartment(UserDepartmentUpdateDTO userDepartmentUpdateDTO){
        String url = splicingAccessToken(getWechatAddressBookSecret(), "user/update");
        WeChatBaseResult weChatBaseResult = BaseRestRequest.postForObject(restTemplate, url, userDepartmentUpdateDTO, WeChatBaseResult.class);
        if(!Objects.equals(weChatBaseResult.getErrCode(), CommonCodeConstant.SUCCESS_CODE)){
            log.error(weChatBaseResult.getErrMsg());
            throw new DefinitionException(ResponseEnum.WECHAT_ERROR_USER_DEPARTMENT_UPDATE);
        }
        return weChatBaseResult;
    }

    /**
     * 读取成员
     *
     * 在通讯录同步助手中此接口可以读取企业通讯录的所有成员的信息，而自建应用可以读取该应用设置的可见范围内的成员信息。
     *
     * 请求方式：GET（HTTPS）
     * 请求地址：https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&userid=USERID
     *
     * 参数说明：
     * 参数 	必须 	说明
     * access_token 	是 	调用接口凭证
     * userid 	是 	成员UserID。对应管理端的帐号，企业内必须唯一。不区分大小写，长度为1~64个字节
     * @param userId
     */
    public UserGetResult getUser(String userId){
        MultiValueMap<String, String> queryParamMap = new LinkedMultiValueMap<>();
        queryParamMap.add("userid", userId);
        String url = splicingAccessToken(getWechatAddressBookSecret(), "user/get", queryParamMap);
        UserGetResult userGetResult = BaseRestRequest.postForObject(restTemplate, url, UserGetResult.class);
        if(!Objects.equals(userGetResult.getErrCode(), CommonCodeConstant.SUCCESS_CODE)){
            log.error(userGetResult.getErrMsg());
            throw new DefinitionException(ResponseEnum.WECHAT_ERROR_USER_GET);
        }
        return userGetResult;
    }
}
